package com.zmj.controller;



import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.zmj.anno.RequestPath;
import com.zmj.entity.Goods;
import com.zmj.entity.Order;
import com.zmj.entity.OrderDetail;
import com.zmj.entity.User;
import com.zmj.service.IOrderService;
import com.zmj.service.impl.OrderServiceImpl;


public class OrderController {

	IOrderService orderService = new OrderServiceImpl();
	
	@RequestPath("/addOrder.shop")
	public String addOrder(HttpServletRequest request){
		
		//1:获取相应的信息(插入订单)
		String addid = request.getParameter("addid"); //地址id
		/*
		 * User ue = (User) request.getSession().getAttribute("user"); int id =
		 * ue.getId();//用户id
		 */	
		float shopCarCount = (float) request.getSession().getAttribute("shopCarCount");//订单总金额
		
		Order oe = new Order();
		oe.setOid(System.currentTimeMillis());//订单编号,是自定义的
		oe.setOname("2020年6月12日 jack买的");
		oe.setUid(1);
		oe.setAddid(Integer.parseInt(addid));
		oe.setOtotal(new BigDecimal(shopCarCount));
		oe.setOdesc("没有什么好处哦的");
		
		//2: 添加一条订单信息(往订单表里面插入一条纪录)
		boolean flag = orderService.addOrder(oe);
		
		//3: 往订单详情表里面,添加纪录
		if(flag){ //添加订单详情
			
			//1:订单编号 
//			oe.getOid();
			
			//用户选中的商品id
			String[] gids = (String[]) request.getSession().getAttribute("gids"); //我们前台勾选中的商品
			
			//购物车
			Map<Integer, Goods> shopCar = (Map<Integer, Goods>) request.getSession().getAttribute("shopCar");
		
			Goods ge;
			OrderDetail ode;
			List<OrderDetail> list = new ArrayList<OrderDetail>();
			
			//将所有的商品详情添加到了list
			for(String id : gids){ 
				int gid=Integer.parseInt(id);
				//获取一条商品详情
				ge = shopCar.get(gid);
				System.out.println(ge);
//				ge.getGid();//2:商品编号
//				ge.getBuynumber();//3:商品数量
//				ge.getGprice().multiply(new BigDecimal(ge.getGdiscount()));//4:成交价格
				
				//将这条纪录插入到订单详情里面;
				ode = new OrderDetail(oe.getOid(),ge.getGid(),ge.getBuynumber(),ge.getGprice().multiply(new BigDecimal(ge.getGdiscount())),"呵呵呵");
				
				ode.setGe(ge);//将商品信息,放到订单详情里面去
				list.add(ode);
			}
			
			//保存商品详情;
			boolean res = orderService.addOrderDetails(list);
			
			if(res){
				
				//1: 我们需要将已经结算的商品从购物车移除;
				for(String gid : gids){
					shopCar.remove(gid);
				}
				
				request.getSession().setAttribute("shopCar", shopCar);
				
				//2: 在我们的支付页(order.jsp) 展示订单的信息[订单详情的信息]
				//这笔订单下面有哪些商品;需要展示商品的详情;
				request.setAttribute("order", oe);//订单信息
				request.setAttribute("detailsList", list);//订单详情
				
				return "order.jsp";
			}else{
				return "fail.jsp";
			}
		}
		
		//返回订单页面,支付
		return "order.jsp";
	}
	
}
